/*********************************************************************************
 *      Copyright:  (C) 2024 LiYi<1751425323@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  mqtt_conf.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(25/04/24)
 *         Author:  LiYi <1751425323@qq.com>
 *      ChangeLog:  1, Release initial version on "25/04/24 11:23:56"
 *                 
 ********************************************************************************/
#include "iniparser.h"
#include "mqtt_conf.h"
#include "dictionary.h"
#include <stdio.h>
#include <string.h>


/*  载入设置参数 */
int get_config(char *path,mqtt_user_data *mqtt,int mode)
{
	dictionary      *ini = NULL;
	const char      *brokeraddress;
	int             brokerport = 0;
	const char      *username;
	const char      *password;
	const char      *clientid;
	const char      *topic;
	int             Qos = 0;

	const char      *method;
	const char      *time;
	const char      *jsonid;
	const char      *identifier;
	const char      *version;
	const char      *def = "error";
	int             notfound = 0;

	if(!path || !mqtt)
	{
		printf("invalid_argument: %s\n",__FUNCTION__);
		return -1;
	}
	ini = iniparser_load(path);

	if(!ini)
	{
		printf("iniparser_load failed!\n");
		return -1;
	}

	brokeraddress = iniparser_getstring(ini,"address:host",def);
	brokerport= iniparser_getint(ini,"address:port",notfound);
	username = iniparser_getstring(ini,"user_name_pwd:username",def);
	password = iniparser_getstring(ini,"user_name_pwd:pwd",def);
	clientid = iniparser_getstring(ini,"clientid:id",def);
	identifier = iniparser_getstring(ini,"ali_json:identifier",def);

	if(mode == SUB)
	{
		topic = iniparser_getstring(ini,"sub_topic:topic",def);

	}

	else if(mode == PUB)
	{
		topic = iniparser_getstring(ini,"pub_topic:topic",def);
		method = iniparser_getstring(ini,"ali_json:method",def);
		//time = iniparser_getstring(ini,"ali_time:time",DEFAULT_TIME);
		//jsonid = iniparser_getstring(ini,"ali_json:id",DEFAULT_JSONID);
		version = iniparser_getstring(ini,"ali_json:version",def);
	}

	else if(mode != SUB && mode != PUB)
	{
		printf("invalid_argument : %s mode!\n",__FUNCTION__);
		return -1;
	}

	strncpy(mqtt->brokeraddress,brokeraddress,SIZE);
	mqtt->brokerport = brokerport;
	mqtt->Qos        = Qos;
	strncpy(mqtt->username,username,SIZE);
	strncpy(mqtt->password,password,SIZE);
	strncpy(mqtt->clientid,clientid,SIZE);
	strncpy(mqtt->topic,topic,SIZE);          
	strncpy(mqtt->identifier,identifier,SIZE);

	if(mode == PUB)
	{
		strncpy(mqtt->method,method,SIZE);
		//strncpy(mqtt->time,time,SIZE);
		//strncpy(mqtt->jsonid,jsonid,SIZE);
		strncpy(mqtt->version,version,SIZE);
	}

	iniparser_freedict(ini);
	return 0;

}



